import 'dart:io';

import 'package:ac/api/ac_urls.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

class AcUploadUtil {
  static Future<String?> uploadFile(File file) async {
    var res = await AcUrls.oss.get(showLoading: false);
    Map<String, dynamic>? data;
    if (res?["code"] == 0) {
      data = res?["data"];
    }
    if (data == null) {
      return null;
    }
    debugPrint('uploadFile data: $data');
    DateTime dateTime = DateTime.now();
    String fileName = file.path.split('/').last;
    String format = fileName.split('.').last;
    int imageTimeName = dateTime.millisecondsSinceEpoch +
        (dateTime.microsecondsSinceEpoch ~/ 1000000);
    String imageName = '$imageTimeName.$format';
    String host = data['host'];
    String dir = data['dir'];
    var filePath = await MultipartFile.fromFile(file.path, filename: fileName);
    final formData = FormData.fromMap({
      'ossaccessKeyId': data['accessKeyId'],
      'policy': data['policy'],
      'signature': data['signature'],
      'callback': data['callback'],
      'key': '$dir/$imageName',
      'file': filePath,
    });
    Dio dio = Dio();
    var response = await dio.post(host, data: formData);
    if (kDebugMode) {
      print("File Upload Back：$response");
    }
    if (response.data != null) {
      if (response.data["data"]["filename"] != null) {
        return response.data["data"]["filename"];
      }
    }
    return null;
  }
}
